const app = getApp()
Page({
  data: {
    status: false,
    num: '请输入兑换数量',
    computed: [7, 8, 9, 4, 5, 6, 1, 2, 3, 0, 'x', '确认']
  },

  onLoad: function (options) {
    if (options.state == 1){
      wx.setNavigationBarTitle({
        title: '红包币兑换消费券'
      })
    }else{
      wx.setNavigationBarTitle({
        title: '消费券兑换红包币'
      })
    }

    let system = wx.getStorageSync('System')
    this.setData({state: options.state, system})
  },

  select (e) {
    let index = e.target.dataset.index,
    num = this.data.computed[index] + '',
    total = this.data.num,
    status = this.data.status 

    if ((index === 10 && !status) || (index === 11 && !status)) {
      //忽略第一次删除和确认
      return
    }

    if(!status){
      this.setData({
        status: true,
        num: num
      })
      return
    }

    if (index == 10) { 
      //删除
      if (total.length === 1) {
        this.setData({
          status: false,
          num: '请输入兑换数量'
        })
        return
      }
      this.setData({num: total.substr(0, total.length - 1)})
      return
    }

    if(index === 11){
      //确认
      total = parseInt(total)
      if(total === 0){
        wx.showToast({
          title: '兑换数量必须大于零',
          icon: 'none'
        })
        return
      }
      let id = wx.getStorageSync("users").id
      let url = 'entry/wxapp/'
      if (this.data.state == 1) {
        url += 'Exchangejifen'
      } else {
        url += 'Exchangehbb' 
      }
      app.util.request({
        url: url,
        data: {
          user_jifen: total,
          user_xiaofeibi: total,
          user_id: id
        },
        success(res){
          wx.showToast({
            icon: 'none',
            title: res.data.result,
            duration: 1800,
            success(){
              if(!res.data.errno){
                setTimeout(() => {
                  wx.navigateBack({})
                }, 1800)
              }
            }
          })
        }
      })
      return
    }

    total = total + num
    this.setData({num: total})
  }
})